package demo2接口使用案例;

import java.util.Arrays;
import java.util.Comparator;

class Student implements Comparable<Student>{
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    //比较student类的年龄大小
    @Override
    public int compareTo(Student o) {
        if(this.age > o.age){
            return 1;
        }
        else if(this.age < o.age){
            return -1;
        }else{
            return 0;
        }
    }
}

//比较器
class AgeComparator implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}

class NameComparator implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}
public interface Test {
    public static void bubbleSort(Comparable[] comparable){
        for(int i = 0; i < comparable.length - 1; i++){
            for(int j = 0; j < comparable.length - 1 - i; j++){
                if(comparable[j].compareTo(comparable[j + 1]) < 0){
                    Comparable tmp = comparable[j];
                    comparable[j] = comparable[j + 1];
                    comparable[j + 1] = tmp;
                }
            }
        }
    }
    public static void main(String[] args) {
        Student stu1 = new Student("zhangsan",20);
        Student stu2 = new Student("lisi",18);

        AgeComparator ageComparator = new AgeComparator();
        System.out.println(ageComparator.compare(stu1, stu2));


        NameComparator nameComparator = new NameComparator();
        System.out.println(nameComparator.compare(stu1, stu2));
    }
    public static void main1(String[] args) {
        Student stu1 = new Student("zhangsan",20);
        Student stu2 = new Student("lisi",18);
        System.out.println(stu1.compareTo(stu2));

        System.out.println("=============");

        //对数组对象进行排序
        Student[] stu = new Student[3];
        stu[0] = new Student("A", 18);
        stu[1] = new Student("B", 15);
        stu[2] = new Student("C", 17);
        Arrays.sort(stu);//调用stu数组元素的compareTo方法，对年龄进行排序
        System.out.println(Arrays.toString(stu));

        System.out.println("=============");
        bubbleSort(stu);
        System.out.println(Arrays.toString(stu));

    }
}
